package com.sun.showcase.biz.basic.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sun.showcase.biz.basic.dao.BaseseCodingRuleDao;
import com.sun.showcase.biz.basic.service.BaseseCodingRuleService;
import com.sun.showcase.client.domain.basic.BaseseCodingRule;
import com.sun.showcase.client.query.basic.BaseseCodingRuleQuery;
import com.sun.showcase.pojo.DataGrid;
import com.sun.showcase.pojo.Pager;
import com.sun.showcase.utils.DateUtils;
import com.sun.showcase.utils.LoginContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("baseseCodingRuleService")
@Transactional
public class BaseseCodingRuleServiceImpl implements BaseseCodingRuleService {
	@Resource
	private BaseseCodingRuleDao baseseCodingRuleDao;
	
	public void setBaseseCodingRuleDao(BaseseCodingRuleDao dao) {
		this.baseseCodingRuleDao = dao;
	}

	public DataGrid datagrid(BaseseCodingRuleQuery baseseCodingRuleQuery) {
		DataGrid j = new DataGrid();
		Pager<BaseseCodingRule> pager  = find(baseseCodingRuleQuery);
		j.setRows(getQuerysFromEntitys(pager.getRecords()));
		j.setTotal(pager.getTotalRecords());
		return j;
	}

	private List<BaseseCodingRuleQuery> getQuerysFromEntitys(List<BaseseCodingRule> baseseCodingRules) {
		List<BaseseCodingRuleQuery> baseseCodingRuleQuerys = new ArrayList<BaseseCodingRuleQuery>();
		if (baseseCodingRules != null && baseseCodingRules.size() > 0) {
			for (BaseseCodingRule tb : baseseCodingRules) {
				BaseseCodingRuleQuery b = new BaseseCodingRuleQuery();
				BeanUtils.copyProperties(tb, b);
				baseseCodingRuleQuerys.add(b);
			}
		}
		return baseseCodingRuleQuerys;
	}

	private Pager<BaseseCodingRule> find(BaseseCodingRuleQuery baseseCodingRuleQuery) {
		Page<BaseseCodingRule> page = PageHelper.startPage(baseseCodingRuleQuery.getPage().intValue(), baseseCodingRuleQuery.getRows().intValue());
		List<BaseseCodingRule> list = baseseCodingRuleDao.findList(baseseCodingRuleQuery);
		Pager<BaseseCodingRule> pager = new Pager<BaseseCodingRule>();
		pager.setRecords(list);
		pager.setTotalRecords(page.getTotal());
		return  pager;
	}
	


	public BaseseCodingRule add(BaseseCodingRuleQuery baseseCodingRuleQuery) {
		BaseseCodingRule t = new BaseseCodingRule();
		BeanUtils.copyProperties(baseseCodingRuleQuery, t);
		t.setActiveFlag("1");//新增默认有效
		t.setCurrentValue(0);
		t.setCreateBy(LoginContextHolder.get().getUserId());//创建人id
		t.setCreateByName(LoginContextHolder.get().getUserName());//创建人姓名
		t.setCreateDate(new Date());
		
		t.setModifiedBy(LoginContextHolder.get().getUserId());
		t.setModifiedByName(LoginContextHolder.get().getUserName());
		t.setModifiedDate(new Date());
		baseseCodingRuleDao.save(t);
		baseseCodingRuleQuery.setId(t.getId());
		return t;
		
	}

	public void update(BaseseCodingRuleQuery baseseCodingRuleQuery) {
		BaseseCodingRule t = baseseCodingRuleDao.getById(baseseCodingRuleQuery.getId());
	    if(t != null) {
	    	BeanUtils.copyProperties(baseseCodingRuleQuery, t);
		}
	    baseseCodingRuleDao.update(t);
	}
	@Transactional(propagation= Propagation.NOT_SUPPORTED)
	public void updateEdit(BaseseCodingRuleQuery baseseDepartmentQuery) {
		BaseseCodingRule t = baseseCodingRuleDao.getById(baseseDepartmentQuery.getId());
	    if(t != null) {
	    	BeanUtils.copyProperties(baseseDepartmentQuery, t);
		}
	    
	    t.setModifiedDate(new Date());
	    
	    baseseCodingRuleDao.updateEdit(t);
	}
	
	public void delete(Long[] ids) {
		baseseCodingRuleDao.deleteAc(ids);
	}

	//逻辑删除 更新状态位
	public void deletePt(Long[] ids) {
		baseseCodingRuleDao.deletePt(ids);
	}

	public BaseseCodingRule get(BaseseCodingRuleQuery baseseCodingRuleQuery) {
		return baseseCodingRuleDao.getById(new Long(baseseCodingRuleQuery.getId()));
	}

	public BaseseCodingRule get(String id) {
		return baseseCodingRuleDao.getById(Long.parseLong(id));
	}

	
	public List<BaseseCodingRuleQuery> listAll(BaseseCodingRuleQuery baseseCodingRuleQuery) {
	    List<BaseseCodingRule> list = baseseCodingRuleDao.findList(baseseCodingRuleQuery);
		List<BaseseCodingRuleQuery> listQuery =getQuerysFromEntitys(list) ;
		return listQuery;
	}

	@Override
	@Transactional(propagation= Propagation.NOT_SUPPORTED)
	public synchronized String getNextCodeById(Long id) {
		BaseseCodingRule t = baseseCodingRuleDao.getById(id);
	    if(t != null) {
	    	if("1".equals(t.getResetModeCode())){
	    		//按月归零
	    		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM");
	    		//判断是否在归零月
	    		if(StringUtils.isEmpty(t.getResetDate()) || t.getResetDate().indexOf(sf.format(new Date()))!=0){
	    			t.setResetDate(DateUtils.format5.format(new Date()));
	    			t.setCurrentValue(t.getResetValue()-1);
	    		}
	    	}else if("0".equals(t.getResetModeCode())){
	    		//按日归零
	    		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
	    		//判断是否在归零日
	    		if(!sf.format(new Date()).equals(t.getResetDate())){
	    			t.setResetDate(DateUtils.format5.format(new Date()));
	    			t.setCurrentValue(t.getResetValue()-1);
	    		}
	    	}
	    	String nextCode = this.getNewCode(t);
	    	t.setMaxValue(nextCode);
	    	t.setCurrentValue(t.getCurrentValue()+1);
	    	BaseseCodingRuleQuery baseseCodingRuleQuery = new BaseseCodingRuleQuery();
	    	BeanUtils.copyProperties(t,baseseCodingRuleQuery);
	    	//更新最大值
	    	this.updateEdit(baseseCodingRuleQuery);
	    	return nextCode;
		}
		return null;
	}
	private String getNewCode(BaseseCodingRule t){
		String result = "";
    	String[] rs = t.getCodingRule().split("_");
    	String normalRuleStr = "";//常量前缀
    	String dateRuleStr = "";//日期编码
    	String numRuleStr = "";//数字编码
    	for(String r :rs){
    		if(r.indexOf("{")>=0 && r.indexOf("}")>=0 && (r.indexOf("YY")>=0 ||r.indexOf("yy")>=0 
    				|| r.indexOf("MM")>=0 || r.indexOf("mm")>=0
    				|| r.indexOf("DD")>=0 || r.indexOf("dd")>=0)){
    			dateRuleStr = r;
    			dateRuleStr = dateRuleStr.replace("mm", "MM");
    			dateRuleStr = dateRuleStr.replace("DD", "dd");
    			dateRuleStr = dateRuleStr.replace("{", "");
    			dateRuleStr = dateRuleStr.replace("}", "");
    			SimpleDateFormat sf = new SimpleDateFormat(dateRuleStr);
	    		result = result + sf.format(new Date());
    		}else if(r.indexOf("{")>=0 && r.indexOf("}")>=0 && (r.indexOf("X")>=0 || r.indexOf("x")>=0)){
    			numRuleStr = r.toUpperCase();
    			numRuleStr = numRuleStr.replace("{", "");
    			numRuleStr = numRuleStr.replace("}", "");
    			result = result + StringUtils.leftPad(String.valueOf(t.getCurrentValue()+1), StringUtils.countMatches(numRuleStr,"X"),"0");
    		}else{
    			normalRuleStr = r;
    			result = result+normalRuleStr;
    		}
    	}
    	return result;
	}
	
}
